package com.biglead.demo.controller;

import com.biglead.demo.anno.AccessLimit;
import com.biglead.demo.common.R;
import com.biglead.demo.service.IUserCategoryService;
import com.biglead.demo.service.SecKillService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 商品秒杀 前端控制器
 * </p>
 *
 * @author 早起的年轻人
 * @since 2023-03-14
 */
@Api(tags="商品秒杀模块")
@RestController()
@RequestMapping("/seckill")
@Slf4j
public class SecKillController {

    @Autowired
    private SecKillService secKillService;

    /**
     * 一般是修改的时候就更新一下 或者是定时任务在秒杀开始前 缓存进来
     * @return
     */
    @ApiOperation(value = "准备秒杀的数据")
    @GetMapping("/startSeckill")
    public R startSeckill() {
        return secKillService.startSeckillInit();
    }

    /**
     * 获取秒杀地址
     */
    // 接口限流
    @AccessLimit(second = 5, maxCount = 2)
    @GetMapping("/path/{id}")
    public R getPath(@PathVariable("id") Long goodsId, @RequestHeader Long userId) {
        // 创建秒杀地址
        return secKillService.createPath(userId, goodsId);
    }

    /**
     * 开始秒杀
     * @param goodsId
     * @param userId
     * @return
     */
    @GetMapping("/{path}/toSecKill/{id}")
    public R toSecKill(@PathVariable("id") Long goodsId,
                       @PathVariable String path,
                       @RequestHeader Long userId) {
        // 验证路径是否合法
        boolean isLegal = secKillService.checkPath(path, userId, goodsId);
        if (!isLegal) {
            return R.error("路径不合法");
        }
        return secKillService.isToSecKill(goodsId, userId);
    }
    /**
     * 获取秒杀结果
     * 返回订单id:秒杀成功
     * 返回 -1 秒杀失败
     * 返回 0 排队中
     */
    @GetMapping("/result/{id}")
    public R getResult(@PathVariable("id") Long goodsId, @RequestHeader Long userId) {
        return secKillService.getResult(goodsId, userId);
    }

}
